#!/usr/local/bin/python2.6
# Created on October 31, 2011
#  by Keith Cherkauer
#
# This program computes annual metrics from the daily streamflow flies
# for the Tippecanoe River and Wildcat Creek.
#

import sys, os
from stats import *
from datetime import datetime, timedelta

NoDataVal = -999.99

# check for proper number of command line arguments
if ( len( sys.argv ) != 5 ):
    sys.stderr.write( "\nUsage: %s <daily flow file> <start year> <end year> <output stat file>\n\n" % sys.argv[0] )
    sys.exit()

# handle command line arguments
InFile = sys.argv[1]
StartYear = int( sys.argv[2] )
EndYear = int( sys.argv[3] )
OutFile = sys.argv[4]

# setup start and end dates for annual processing
#  - using USGS water year that starts in October 1 of any given year.
StartDate = datetime( StartYear, 1, 1 )
EndDate   = datetime( EndYear, 1, 1 )

# prepare data array
NumYears = EndYear - StartYear +1
ObsValues = [0] * NumYears

# open and read input file
if os.path.isfile( InFile ):
    # file found, so open and read contents
    fin = open( InFile, "r" )
    lines = fin.readlines()
    fin.close()
    a = len(lines)
    print a
else:
    # file not available
    sys.stderr.write( "ERROR: Unable to find input file, %s.\n" % InFile )
    sys.exit()

NextDate = StartDate
for yidx in range(NumYears):
    LastDate = NextDate
    NextDate = datetime( NextDate.year+1, NextDate.month, NextDate.day )
    NumDays = (NextDate - LastDate).days
    ObsValues[yidx]=[-999.99]*NumDays

# parse file data
for lidx in range(len(lines)):
    lines[lidx] = lines[lidx].strip().split("\t")##strip the \n character from the line and split the line on tab
    lines[lidx][0] = datetime.strptime( lines[lidx][0], "%Y/%m/%d" )

# establish file start and end dates
FileStart = lines[0][0]
FileEnd   = lines[-1][0]

# check that data set is long enough
if StartDate < FileStart:
    sys.stderr.write( "ERROR: Starting date of file (%s) is after the requested starting date for the output table (%s).\n" % ( FileStart.strftime("%Y-%m-%d"), StartDate.strftime("%Y-%m-%d") ) )
    sys.exit()
if EndDate > FileEnd:
    sys.stderr.write( "ERROR: Ending date of file (%s) is before the requested ending date for the output table (%s).\n" % ( FileEnd.strftime("%Y-%m-%d"), EndDate.strftime("%Y-%m-%d") ) )
    sys.exit()

# parse file data
LastDayOfRange = datetime( EndDate.year+1, EndDate.month, EndDate.day )
for lidx in range(len(lines)):
    dt = (lines[lidx][0])
    if dt >= StartDate and dt < LastDayOfRange:
        yearIndex = dt.year-StartDate.year
        dayIndex = dt.toordinal() - datetime(dt.year,1,1).toordinal()
        print "dt", dt
        ObsValues[yearIndex][dayIndex]=float(lines[lidx][1])
        
print ObsValues
fout = open( OutFile, "w" )
fout.write( "Year\tMean\tMax\tMin\tStdDev\tTqmean\tRBindex\n" )
for yidx in range( NumYears ):
    fout.write("%i" % (StartYear+yidx+1) ) # water years are numbered based on the year with more months
    MetricVal = get_mean( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_max( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_min( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_stdev( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_Tqmean( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_RBindex( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f\n" % MetricVal[0] ) 


